/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.minetsh.imaging.sample;

import me.minetsh.imaging.photoview.bean.ImageItem;
import me.minetsh.imaging.imageData.ImagePicker;
import me.minetsh.imaging.photoview.ui.ImageGridAbility;
import me.minetsh.imaging.view.PhotoUtil;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.global.resource.NotExistException;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * GallerySampleAbility
 *
 * @since 2021-07-27
 */
public class GallerySampleAbility extends Ability {
    private static final HiLogLabel HILOGLABEL = new HiLogLabel(HiLog.LOG_APP, 0x222, "my_app");
    private RadioButton rb_single, rb_multi;
    private TextField et_max_count;
    private Button btn_choose, btn_custom;
    private ImagePicker imagePicker;
    ArrayList<ImageItem> images = null;
    private ListContainer gallerysample_list;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_gallery_sample);
        ResourceManager resManager = this.getResourceManager();
        imagePicker = ImagePicker.getInstance();
        imagePicker.setMultiMode(true);
        try {
            int color = resManager.getElement(ResourceTable.Color_colorPrimaryDark).getColor();
            getWindow().setStatusBarColor(color);
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.fillInStackTrace();
        }

        rb_single = (RadioButton) findComponentById(ResourceTable.Id_rb_single);
        rb_multi = (RadioButton) findComponentById(ResourceTable.Id_rb_multi);
        et_max_count = (TextField) findComponentById(ResourceTable.Id_et_max_count);
        rb_multi.setChecked(true);
        btn_choose = (Button) findComponentById(ResourceTable.Id_btn_choose);
        btn_custom = (Button) findComponentById(ResourceTable.Id_btn_custom);
        gallerysample_list = (ListContainer) findComponentById(ResourceTable.Id_gallerysample_list);
        gallerysample_list.setOrientation(Component.HORIZONTAL);

        et_max_count.addTextObserver((text, start, before, count) -> {
            StringBuilder builder = new StringBuilder();
            for (int index = 0; index < text.length(); index++) {
                String result = text.substring(index, index + 1);
                try {
                    Integer.parseInt(result);
                    builder.append(result);
                } catch (NumberFormatException e) {
                    text = text.replace(result, "");
                    HiLog.info(HILOGLABEL, "error-->" + e);
                }
            }
            if (!et_max_count.getText().equals(text)) {
                et_max_count.setText(text);
            }

        });

        btn_choose.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                imagePicker.setStatus(0);
                if (rb_single.isChecked()) imagePicker.setMultiMode(false);
                else if (rb_multi.isChecked()) {
                    imagePicker.setMultiMode(true);
                }
                imagePicker.setCrop(true);
                chooseImagesFromCustomAlbum();
            }
        });

        btn_custom.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                imagePicker.setStatus(1);
                if (rb_single.isChecked()) imagePicker.setMultiMode(false);
                else if (rb_multi.isChecked()) {
                    imagePicker.setMultiMode(true);
                }
                // 自定义相册
                chooseImagesFromCustomAlbum();
            }
        });

    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        try {
            super.onAbilityResult(requestCode, resultCode, resultData);
            if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
                if (resultData != null && requestCode == 100) {
                    images = (ArrayList<ImageItem>) resultData.getSerializableParam(ImagePicker.EXTRA_RESULT_ITEMS);

                    MyAdapter adapter = new MyAdapter(images);
                    gallerysample_list.setItemProvider(adapter);
                }
            }
        }catch (Exception e){
            images = new ArrayList<>();
        }
    }

    private void chooseImagesFromCustomAlbum() {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName(ImageGridAbility.class.getName())
                .build();
        intent.setOperation(operation);
        intent.setParam("max_count",et_max_count.getText());
        startAbilityForResult(intent, 100);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private class MyAdapter extends BaseItemProvider {

        private List<ImageItem> items;

        public MyAdapter(List<ImageItem> items) {
            this.items = items;
        }

        public void setData(List<ImageItem> items) {
            this.items = items;
            notifyDataChanged();
        }

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public ImageItem getItem(int position) {
            return items.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
            Image imageView;
            if (component == null) {
                imageView = new Image(GallerySampleAbility.this);
                ShapeElement element = new ShapeElement();
                element.setRgbColor(RgbColor.fromArgbInt(Color.getIntColor("#88888888")));
                imageView.setBackground(element);
            } else {
                imageView = (Image) component;
            }

            ComponentContainer.LayoutConfig layoutConfig =new ComponentContainer.LayoutConfig();
            layoutConfig.height = 300;
            layoutConfig.width = 300;
            layoutConfig.setMarginRight(5);
            imageView.setLayoutConfig(layoutConfig);
            imageView.setScaleMode(Image.ScaleMode.CLIP_CENTER);
            imageView.setPixelMap(PhotoUtil.getPixelMapByUri(getContext(),getItem(position).uriSchema));
            return imageView;
        }

    }
}